import React, { useState, useCallback, useEffect } from 'react';
import { Modal, Table } from 'antd';
import { getNumGroupDetail } from '../../../../servers/servers';
import { transformTableData } from 'utils/tools';

/**
 * 号码组信息详情props
 */
interface Iprops {
  // 对话框可见性
  visible: boolean;
  // 所要展示的数据详情
  callGroupId: number;
  // 对话框关闭时的回调
  onClose: () => void;
}

/**
 * 弹窗-号码组详情
 */
export const NumGroupCheckDetail: React.FC<Iprops> = ({ visible, callGroupId, onClose }) => {
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(5);
  //  数据总数
  const [pageTotal, setTotal] = useState<number>(0);
  // Table表头列
  const [tableTit, setTableTit] = useState([]);
  // Table数据
  const [tableData, setTableData] = useState([]);
  const [tableLoading, setTableLoading] = useState(false);

  /**
   * Table数据加载
   */
  const getTableList = useCallback(async () => {
    if (!callGroupId) {
      return;
    }
    setTableLoading(true);
    try {
      const res = await getNumGroupDetail({
        pageNo: current,
        pageSize: pageSize,
        callGroupId,
      });

      console.log('号码组详情--原始数据', res.data);
      const arr: any = transformTableData(res.data);
      arr[0].unshift({
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      });
      for (let i = 0; i < arr[1].length; i++) {
        arr[1][i].index = i + 1 + pageSize * (current - 1);
      }
      console.log(arr[1], 'list加入index后');
      // 数据转换
      setTableTit(arr[0]);
      setTableData(arr[1]);
      setTotal(Number(res.count) || 0);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [callGroupId, current, pageSize]);
  // 数据初始化 && 数据更新
  useEffect(() => {
    if (visible) {
      getTableList();
    }
  }, [getTableList, visible]);

  return (
    <div>
      <Modal
        width="900px"
        title="号码组详情"
        visible={visible}
        footer={null}
        destroyOnClose
        onCancel={onClose}
      >
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            columns={tableTit}
            dataSource={tableData}
            rowKey="index"
            scroll={{ x: 'max-content' }}
            pagination={{
              showSizeChanger: true,
              pageSizeOptions: ['5', '10', '20', '50', '100'],
              total: pageTotal,
              showTotal: total => `共${total}条`,
              current: current,
              pageSize: pageSize,
              // 改条数/页
              onShowSizeChange: (current, size) => {
                setPageSize(size);
              },
              // 改页码
              onChange: current => {
                setCurrent(current);
              },
            }}
          />
        </div>
      </Modal>
    </div>
  );
};
